package com.du.linandroid.biz;

import android.app.Activity;

import com.du.linandroid.callback.CallBack;
import com.du.linandroid.util.LLog;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WbAuthListener;
import com.sina.weibo.sdk.auth.WbConnectErrorMessage;
import com.sina.weibo.sdk.auth.sso.SsoHandler;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by DuZiLin on 2018/4/3.
 */

class WeiboService implements IService{
    private Activity mActivity;
    private OkHttpClient okHttpClient = new OkHttpClient();
    public WeiboService(Activity mActivity) {
        this.mActivity = mActivity;
    }

    @Override
    public void login(CallBack loginCallBack) {
        if(ApiHolder.mSsoHandler == null){
            ApiHolder.mSsoHandler = new SsoHandler(mActivity);
        }
        ApiHolder.mSsoHandler.authorize(new WeiboInnerListener(loginCallBack));

    }

    private class WeiboInnerListener implements WbAuthListener{
        CallBack callBack;

        public WeiboInnerListener(CallBack callBack) {
            this.callBack = callBack;

        }

        @Override
        public void onSuccess(Oauth2AccessToken oauth2AccessToken) {
            LLog.d("weibo success!");
            if(oauth2AccessToken.isSessionValid()){
                getUserinfo(oauth2AccessToken);
            }
        }

        private void getUserinfo(Oauth2AccessToken oauth2AccessToken) {
            Request request = new Request.Builder().url("https://api.weibo.com/2/users/show.json?appkey=" + ApiHolder.WEIBO_APP_KEY +"&access_token" + oauth2AccessToken.getToken() + "&uid=" + oauth2AccessToken.getUid()).build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    LLog.d(response.body().string());
                }
            });
        }

        @Override
        public void cancel() {

        }

        @Override
        public void onFailure(WbConnectErrorMessage wbConnectErrorMessage) {
            LLog.d("weibo onFailure!" + wbConnectErrorMessage.getErrorMessage());
        }
    }

}
